var fangdai = {
	els: {
		//问题列表
		qList: $("#QuestionList"),
		//下一步
		next: $("#BtnNext"),
		//上一步
		pre: $("#BtnPre"),
		//专家提示
	},
	//数据分层
	dataList:{
		//城市列表
		city: data.hpcity,
		//选项列表
		element: data.city_element,
		//政策列表
		policy: data.city_policy,
		//提示列表
		tips: data.calc_desc
	},
	//状态列表
	statusList: {
		//能买几套房
		canBuy: {
			key: false,
			data: 0
		},
		//拥有几套房
		nowHave: {
			key: false,
			data: 0
		},
		//此次购买算第几套
		nowCount: {
			key: false,
			data: 0
		}
	},
	//数据变量
	varList: {
		token: "can_buy",
		cityId: "10000",
		//每一步的字段名
		varName: "city_id",
		//每一步的显示名
		varText: "",
		//每一步的
		title: "",
		eleId: "",
		canBuy: 0
	},
	//计算结果数据结构
	//线性顺序key存储
	listKey: [],
	//json结构存储
	resultList:{},
	/*
		{
			id: "",步骤id
			title: "",//标题描述
			answer: ""//回答值
		}
	*/
	init: function(){
		//window.data = JSON.parse(data);
		//alert(data);
		var me = fangdai;
		//绑定下一步、上一步操作事件
		fangdai.bindAction();
		//初始化城市列表
		fangdai.drawList(fangdai.getCity());
	},	
	//绑定下一步、上一步事件操作
	bindAction: function(){
		var me = fangdai;
		fangdai.els.next.click(function(){
			var _selRadio = $('input[name=' + fangdai.varList.varName + ']:checked');
			var _value = _selRadio.val();
			var _text = _selRadio.attr("desc");
			//console.log(_value);
			//console.log(_text);
			fangdai.next(_value, _text);
		});
		fangdai.els.pre.click(function(){
			//fangdai.next("1", "本地独立户口");
			fangdai.pre();
		});
	},
	//上一步
	pre: function(){
		if(fangdai.listKey.length == 1){
			fangdai.resultList = {};
			fangdai.listKey = [];
			fangdai.varList = {
				token: "can_buy",
				cityId: "10000",
				//每一步的字段名
				varName: "city_id",
				//每一步的显示名
				varText: "",
				//每一步的
				title: "",
				eleId: "",
				canBuy: 0
			};
			//初始化城市列表
			fangdai.drawList(fangdai.getCity());
		}else{
			delete fangdai.resultList[fangdai.listKey[fangdai.listKey.length-1]];
			fangdai.listKey.pop();

			console.log(fangdai.listKey[fangdai.listKey.length-1]);
			var _last = fangdai.resultList[fangdai.listKey[fangdai.listKey.length-1]];
			fangdai.drawList(_last.drawData);
			//fangdai.varList.eleId = "";
			fangdai.varList.eleId = _last.id;
		}
	},
	//下一步执行
	next: function(id,text){
		//console.log(id);
		//console.log(text);
		//追加记录
		if(fangdai.varList.varName == "city_id"){
			fangdai.varList.cityId = id;
			//追加计算结果列表
			fangdai.resultList["city_id"]["value"] = id;
			fangdai.resultList["city_id"]["varText"] = text;
		}else{
			if(fangdai.resultList[fangdai.varList.eleId]){
				//追加计算结果列表
				console.log(fangdai.resultList[fangdai.varList.eleId]);
				fangdai.resultList[fangdai.varList.eleId]["value"] = id;
				fangdai.resultList[fangdai.varList.eleId]["varText"] = text;
			}
		}

		//计算
		var result = fangdai.calcu();
		//如果是继续
		if(result.type == "goon"){
			var __tip = fangdai.getTips();
			var __result = fangdai.getElementList();
			var _iosData = JSON.stringify({
				type: "goon",
				title: __result.title,
				data: __result.data,
				tips: __tip.tip,
				qaList: __tip.qa
			});
			console.log(_iosData);
			return _iosData;
			//me.getElementList();
		}			
		//如果是成功
		if(result.type == "success"){
			var _result = 0;
			//如果成功后，则转身num_have处理逻辑
			if(fangdai.varList.token == "loan_index"){
				fangdai.statusList.nowCount.key = true;
				fangdai.statusList.nowCount.data = result.value;
			}
			if(fangdai.varList.token == "num_have"){
				fangdai.statusList.nowHave.key = true;
				//console.log("result.value");
				//console.log(result.value);
				fangdai.statusList.nowHave.data = result.value;
				fangdai.varList.token = "loan_index";
				if(fangdai.statusList.canBuy.data - fangdai.statusList.nowHave.data <= 0){
					return JSON.stringify({
						type: "fail",
						data: "您不能买房",
						listKey: fangdai.listKey,
						resultList: fangdai.resultList
					});
				}
			}
			if(fangdai.varList.token == "can_buy"){
				fangdai.statusList.canBuy.key = true;
				fangdai.statusList.canBuy.data = result.value;
				fangdai.varList.token = "num_have";
			}
			//console.log("状态列表：" + JSON.stringify(me.statusList));
			if(fangdai.statusList.nowCount.key == true){
				//console.log(fangdai.resultList);
				//console.log("您可以购买：" + (fangdai.statusList.canBuy.data - fangdai.statusList.nowHave.data));
				//console.log("此次购买算做第" + (fangdai.statusList.nowCount.data) + "套房");
				var _resultToIos = JSON.stringify({
					type: "success",
					listKey: fangdai.listKey,
					resultList: fangdai.resultList,
					canBuy: fangdai.statusList.canBuy.data,
					nowHave: fangdai.statusList.nowHave.data,
					nowCount: fangdai.statusList.nowCount.data,
				});
				//console.log(_resultToIos);
				return _resultToIos;

			}else{
				fangdai.calcu();
				fangdai.getTips();
				var __result = fangdai.getElementList();
				var __tip = fangdai.getTips();
				return JSON.stringify({
					type: "goon",
					title: __result.title,
					data: __result.data,
					tips: __tip.tip,
					qaList: __tip.qa
				});
			}
		}
		if(result.type == "fail"){
			//console.log(fangdai.listKey);
			//console.log(fangdai.resultList);
			return JSON.stringify({
				type: "fail",
				data: "您不能买房",
				listKey: fangdai.listKey,
				resultList: fangdai.resultList
			});

		}
	},
	//获取城市
	getCity: function(){
		var me = fangdai;
		var _result = {
			title: "您所在的城市",
			data: []
		};
		var city = data.hpcity;
		$(city).each(function(index, item){
			_result.data.push({
				value: item.id,
				desc: item.name
			});
		});
		fangdai.varList.varName = "city_id";
		window.cityData = JSON.stringify(_result);
		//追加计算结果列表
		fangdai.listKey.push("city_id");
		fangdai.resultList["city_id"] = {
			id: "city_id",
			value: "0",
			varName: "city_id",
			varText: "北京",
			title: "您所在的城市：",
			token: "can_buy",
			drawData: _result
		};
		return _result;
	},
	//获取描述和问答
	getTips: function(){
		var tipsData = fangdai.dataList.tips;
		//console.log(fangdai.listKey);
		//id = fangdai.varList.eleId;
		var id;
		var elementData = fangdai.dataList.element;
		$(elementData).each(function(index, item){
			if(parseInt(item.id) == fangdai.varList.eleId){
				//console.log(true);
				id = item.element_id;
			}
		});
		cityid = fangdai.varList.cityId;
		//console.log("eleId:" + id);
		//console.log("cityid:" + cityid);
		//console.log(tipsData);
		var _result = {
			tip: "",
			qa: []
		};
		$(tipsData).each(function(index, item){
			if(item.element_id == id && item.city_id == cityid){
				//console.log("title:" + item.title);
				_result.tip = item.tips;
				if(item.sample1 != ""){
					/*
					_result.qa.push(
						{
							q: item.sample1.split("\r\n")[0],
							a: item.sample1.split("\r\n")[1]
						}
					);
					*/
					_result.qa.push(item.sample1.split("\r\n")[0]);
					_result.qa.push(item.sample1.split("\r\n")[1]);
				}
				if(item.sample2 != ""){
					_result.qa.push(item.sample2.split("\r\n")[0]);
					_result.qa.push(item.sample2.split("\r\n")[1]);
				}
				if(item.sample3 != ""){
					_result.qa.push(item.sample3.split("\r\n")[0]);
					_result.qa.push(item.sample3.split("\r\n")[1]);
				}
			}
		});
		//console.log(!_result.data);
		if(_result.tip == ""){
			$(tipsData).each(function(index, item){
				if(item.element_id == id && item.city_id == "10000"){
					//console.log("title:" + item.title);
					_result.tip = item.tips;
					if(item.sample1 != ""){
						_result.qa.push(item.sample1.split("\r\n")[0]);
						_result.qa.push(item.sample1.split("\r\n")[1]);
					}
					if(item.sample2 != ""){
						_result.qa.push(item.sample2.split("\r\n")[0]);
						_result.qa.push(item.sample2.split("\r\n")[1]);
					}
					if(item.sample3 != ""){
						_result.qa.push(item.sample3.split("\r\n")[0]);
						_result.qa.push(item.sample3.split("\r\n")[1]);
					}
				}
			});		
		}
		//if(id == "11" && _result.tip == ""){
		//	_result.tip = "购房贷款受理地与房产所在地相同，原则上您在哪里买房子，就在哪里申请贷款";
		//}
		//console.log(_result);
		return _result;
	},
	//获取枚举列表
	getElementList: function(){
		//console.log(id);
		var me = fangdai;
		//计算
		id = fangdai.varList.eleId;
		cityid = fangdai.varList.cityId;
		var elementData = fangdai.dataList.element;
		var _result = {
			title: "",
			data: []
		};
		$(elementData).each(function(index, item){
			if(item.id == id && item.city_id == cityid){
				//console.log("title:" + item.title);
				_result.title = item.title;
				_result.data = item.data;
				fangdai.varList.varName = item.var_name;
			}
		});
		//console.log(!_result.data);
		if(_result.data.length == 0){
			$(elementData).each(function(index, item){
				if(item.id == id && item.city_id == "10000"){
					//console.log("title:" + item.title);
					_result.title = item.title;
					_result.data = item.data;
					fangdai.varList.varName = item.var_name;
				}
			});
		}
		//console.log(_result);
		fangdai.varList.title = _result.title;
		//console.log(fangdai.resultList[fangdai.listKey[fangdai.listKey.length-1]]);
		//追加计算结果列表
		fangdai.listKey.push(fangdai.varList.eleId);
		fangdai.resultList[fangdai.varList.eleId] = {
			value: "",
			id: fangdai.varList.eleId,
			title: _result.title + "：",
			varName: fangdai.varList.varName,
			token: fangdai.varList.token,
			drawData: _result
		};

		fangdai.drawList(_result);
		return _result;
	},
	//获取下一个问题id
	getNextQ: function(data){
		var me = fangdai;
		token = fangdai.varList.token;
		var branch = {};
		//计算问题出现数
		$(data).each(function(index, item){
			//console.log(item);
			$(item.require).each(function(subindex,subitem){
				//console.log(subitem);
				if(branch[subitem.id]){
					branch[subitem.id] += 1;
				}else{
					branch[subitem.id] = 1;
				}
			});
		});
		//步骤id按出现次数排序
		var _dataList = [];
		for(var key in branch){
			_dataList.push({
				id: key,
				data: branch[key]
			});
		}
		_dataList.sort(function(a,b){return a["data"]>b["data"]?1:-1});
		_dataList.reverse();
		//console.log(_dataList);
		//console.log("resultList:" + JSON.stringify(me.resultList));
		for(var i = 0;i<_dataList.length; i++){
			//console.log("resultID:" + _dataList[i].id);
			if(!fangdai.resultList[_dataList[i].id]){
				//console.log("Qid:" + _dataList[i].id);
				//返回问题id
				return _dataList[i].id;
			}
		}
	},
	//计算结果逻辑
	calcu: function(){
		console.log("计算");
		var me = fangdai;
		token = fangdai.varList.token;
		var branch = {};
		var policyList = fangdai.dataList.policy;
		var policy;
		var _resultData = {};
		var _passKey = false;
		//输出
		var _result = {
			type: "",
			value: ""
		};

		//console.log(me.varList.cityId);
		//获取匹配城市项
		$(policyList).each(function(index, item){
			//匹配城市ID和token
			if((fangdai.varList.cityId == item.city_id) && (token == item.token)){
				policy = item;
			}
		});
		//如果没有找到匹配项，则按默认匹配
		if(!policy){
			$(policyList).each(function(index, item){
				//匹配城市ID和token
				if((item.city_id == "10000") && (token == item.token)){
					policy = item;
				}
			});	
		}
		console.log("计算1");
		var emptyItemList = [];
		//计算结果
		//$(policy.data).each(function(index, item){
		for(var index = 0;index < policy.data.length; index++){
			var item = policy.data[index];
			//console.log(item);
			var _branchResult = true;
			//console.log("relength:" + item.require.length);

			for(var subindex = 0; subindex<item.require.length; subindex++){
				var subitem = item.require[subindex];
				if(fangdai.resultList[subitem.id]){
					//console.log("data：" + subitem.data);
					//console.log("me.resultList");
					//console.log(me.resultList);
					//console.log("subitem");
					//console.log(subitem);
					if( subitem.data.indexOf(fangdai.resultList[subitem.id].value) == -1){
						//console.log("失败");
						_branchResult = false;
						break;
					}
				}
				else if(_branchResult == true){
					_branchResult = 'empty';
				}
			}
			//当计算成功后
			if(_branchResult == true){
				//console.log(item.result_val);
				_result = {
					type: "success",
					value: item.result_val
				};

				return _result;
			}else if(_branchResult == 'empty'){
				emptyItemList.push(item);
			}

		}
		//console.log("emptyItemList");
		//console.log(emptyItemList);

		//console.log("_branchResult");
		//console.log(_branchResult);
		//如果失败
		if(emptyItemList.length == 0){
			if(fangdai.varList.token == "loan_index"){
				_result = {
					type: "success",
					value: parseInt(policy.default)
				};
				return _result;	
			}

			//console.log("item.result_val");
			//console.log(item.result_val);
			_result = {
				type: "fail",
				value: "您不能买房子"
			};

			return _result;
		}
		
		console.log("计算2");

		//如果继续计算
		var _eleId = fangdai.getNextQ(emptyItemList);
		fangdai.varList.eleId = _eleId;
		fangdai.varList.token = token;
		_result = {
			type: "goon",
			value: fangdai.varList.eleId
		};

		return _result;
	},
	//渲染列表
	drawList: function(data){
		//console.log(fangdai.resultList);
		//console.log(fangdai.listKey);
		//console.log(fangdai.varList);
		var me = fangdai;

		var _listDom = "";
		var _cityOther = "";
		$(data.data).each(function(index, item){
			var _itemDom = fangdai.tpl.pListItem
							.replace("{name}", fangdai.varList.varName)
							.replace("{value}", item.value)
							.replace(/{text}/g, item.desc);
			_listDom += _itemDom;
		});
		//console.log(data.data);
		fangdai.els.qList.html(_listDom);
		return data.data;
	},
	//模板
	tpl: {
		//问题列表模板
		pListItem: '<p{title}><label><input type="radio" name="{name}" value="{value}" desc="{text}" /></label><span class="label-text">{text}</span></p>'
	}
};

fangdai.init();

